﻿using AutoMapper;
using ERP.Inventory.Api.Write.Application.Command.库存管理;
using ERP.Inventory.Domain.库存管理;
using ERP.Inventory.Errorcode;
using ERP.Inventory.Infastructure.Interface;
using MediatR;

namespace ERP.Inventory.Api.Write.Application.Handler.库存管理
{
    public class UpdateCheckHandler : IRequestHandler<UpdateCheckCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<CheckModel> CheckRepo;
        private readonly IMapper mapper;

        public UpdateCheckHandler(IBaseRepository<CheckModel> CheckRepo, IMapper mapper)
        {
            this.CheckRepo = CheckRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(UpdateCheckCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();
            var check = CheckRepo.GetAll().Where(x => x.InvenCode == request.InvenCode && x.Id != request.Id).FirstOrDefault();
            if (check != null)
            {
                res.Message = "盘点编号已存在";
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
            }
            var entity = mapper.Map(request, check);
            var r = CheckRepo.Update(entity).Result;
            if (r > 0)
            {
                res.Message = "修改成功";
                res.Code = ApiEnum.Ok;
                res.Data = r;
            }
            else
            {
                res.Message = "修改失败";
                res.Code = ApiEnum.Error;
                res.Data = r;
            }
            return Task.FromResult(res);
        }
    }
}
